<template>
  <!-- 添加卡片 -->
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <el-button type="primary" :icon="Plus" @click="showDialogByAdd"
            >添加</el-button
          >
        </div>
      </template>
      <!-- 表格 -->
      <el-table
        :data="trademarkList"
        v-loading="loading"
        align="center"
        border
        style="width: 100%"
      >
        <el-table-column align="center" type="index" label="序号" width="200" />
        <el-table-column
          align="center"
          prop="tmName"
          label="品牌"
          width="300"
        />
        <el-table-column align="center" label="品牌LOGO">
          <template v-slot="{ row }">
            <img :src="row.logoUrl" alt="" style="width: 100px"
          /></template>
        </el-table-column>
        <el-table-column align="center" prop="address" label="操作">
          <template v-slot="{ row, $index }">
            <el-button
              @click="editTrademark(row)"
              title="编辑"
              type="warning"
              size="small"
              :icon="Edit"
            ></el-button>
            <el-button
              @click="removeTrademark(row)"
              title="删除"
              type="danger"
              size="small"
              :icon="Delete"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        style="margin-top: 15px"
        v-model:currentPage="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[3, 5, 10, 20]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout=" prev, pager, next, jumper, ->, sizes,total "
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 弹出框 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="`${trademark.id ? '修改' : '添加'}品牌`"
    >
      <!-- 表单 -->
      <el-form ref="ruleFormRef" :model="trademark" :rules="rules">
        <el-form-item label="品牌名称" :label-width="formLabelWidth" prop="tmName">
          <el-input v-model="trademark.tmName"  autocomplete="off"  />
        </el-form-item>
        <el-form-item label="品牌LOGO" :label-width="formLabelWidth" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="`${BASE_URL}/admin/product/fileUpload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademark.logoUrl"
              :src="trademark.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip text-red">
                只能上传jpg/png 文件，且不超过2M大小
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitTrademarkInfo(ruleFormRef)"
            >提交</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
export default {
  name: "Trademark",
};
</script>

<script lang="ts" setup>
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import {
  reqGetTrademarkListData,
  reqSaveTrademarkInfo,
  reqDelTrademarkInfo,
  updateTrademarkInfo,
} from "@/api/product/trademark";
import { onMounted } from "vue";
import { ref, reactive } from "vue";
// 引入records的类型限制,要加type
import type { trademarkModelList } from "@/api/product/model/trademark";
import type { trademarkModel } from "@/api/product/model/trademark";
const small = ref(false);
const background = ref(false);
const disabled = ref(false);
console.log("meta", import.meta.env);

// 定义加载样式
const loading = ref(true);

// 分页器部分： 定义分页数据
const currentPage = ref(1); //默认是第一页
const pageSize = ref(3); //默认三条
const total = ref(0);

// 单击当前页码实现分页
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  currentPage.value = val;
  getTrademarkListData();
};

// 修改每页显示的条数
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  console.log(`page-size`, val);
  getTrademarkListData();
};

// 品牌部分
// 定义品牌数据
let page = ref(1);
let limit = ref(5);
let trademarkList = ref<trademarkModelList>([]);

// 收集品牌数据，初始为空
const trademarkInfo = reactive<trademarkModel>({
  tmName: "",
  logoUrl: "",
});
// 获取品牌数据
const getTrademarkListData = async () => {
  const result = await reqGetTrademarkListData(
    currentPage.value,
    pageSize.value
  );
  console.log(result);
  trademarkList.value = result.records;
  total.value = result.total;
  // pageSize.value = result.size
  // 请求成功后隐藏loading效果
  loading.value = false;
};

// 弹出框部分
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";

// 点击添加按钮 弹出框
// 再次单击`+添加`按钮时，应该要清空之前的内容，我们可以定义一个函数来处理一下
const initTrademark = () => ({ tmName: "", logoUrl: "" });
const trademark = reactive<trademarkModel>(initTrademark());
const showDialogByAdd = () => {
  // 再次整合数据到trademark assign优化繁琐的重新赋值
  // trademark.tmName = ''
  // trademark.logoUrl = ''
  Object.assign(trademark, initTrademark());
  delete trademark.id; //清楚id 因为从initTrademark仍然存留id
  dialogFormVisible.value = true;
  // 清空上一次添加失败仍然存在的校验规则
  ruleFormRef.value?.clearValidate()
};

// +图片 逻辑
import { ElMessage } from "element-plus";
const imageUrl = ref("");
const BASE_URL = import.meta.env.VITE_API_URL;
import type { UploadProps } from "element-plus";

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  console.log(response, uploadFile);
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  trademark.logoUrl = response.data;
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const imgType = ["image/jpeg", "images/jpg", "images/png"];
  // if (rawFile.type !== "image/jpeg") {
  if (!imgType.includes(rawFile.type)) {
    ElMessage.error("上传图片的格式只能是jpg/png/jpeg,请重新选择");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小不能超过2M,请重新选择...!");
    return false;
  }
  return true;
};

// 弹出框的表单校验
import type { FormInstance, FormRules } from "element-plus";
const ruleFormRef = ref<FormInstance>(); // 定义一个ref值 和el-form绑定
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: "请添加品牌名称", trigger: "blur" },
    { min: 2, max: 8, message: "字符长度在2到8之间", trigger: "blur" },
  ],
  logoUrl: [
    { required: true, message: "请选择要上传的图片", trigger: "change" },
  ],
});

// const resetForm = (formEl: FormInstance | undefined) => {
//   if (!formEl) return;
//   formEl.resetFields();
// };

// 删除品牌
import { ElMessageBox } from "element-plus";
const removeTrademark = (row: trademarkModel) => {
  console.log("del", row);
  ElMessageBox.confirm(`您确认要删除${row.tmName}吗?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      // 发送请求删除数据
      await reqDelTrademarkInfo(row.id as number);
      console.log("删除成功");

      ElMessage({
        type: "success",
        message: "删除成功.....",
      });
      // 查看党倩倩是否有数据，如果没有就往前一页，再重新发送请求
      currentPage.value =
        trademarkList.value.length > 1
          ? currentPage.value
          : currentPage.value - 1;
      getTrademarkListData();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除......",
      });
    });
};

// 编辑品牌
const editTrademark = (row: trademarkModel) => {
  dialogFormVisible.value = true;
  // 显示品牌数据，因为数据是响应式的，会渲染出来
  Object.assign(trademark, row);
  // 再次编辑处也要清空校验规则
  ruleFormRef.value?.clearValidate()
};

// 确定按钮提交弹出框 确定按钮要判断是添加还是修改
const submitTrademarkInfo = async (formEl: FormInstance | undefined) => {
  // 如有有id就是修改，没有就是添加
  console.log("确定提交事件");
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (trademark.id) {
        // 修改数据请求
        updateTrademarkInfo(trademark);
      } else {
        // 添加数据请求
        reqSaveTrademarkInfo(trademark);
      }
      console.log("update/add"); //这里result就是null，因为服务端返回的data是null

      ElMessage.success("品牌上传成功");
      // ElMessage({
      //   type:'success',
      //   message:'品牌上传成功'
      // })
      // 隐藏对话框
      dialogFormVisible.value = false;
      // 跳转回第一页，重新发送请求
      !trademark.id ? (currentPage.value = 1) : currentPage.value
      getTrademarkListData();
    } else {
      console.log("error submit!", fields);
    }
  });
  let result;
};

onMounted(() => {
  getTrademarkListData();
});
</script>
<style scoped >
.el-button--text {
  margin-right: 15px;
}
.el-select {
  width: 300px;
}
.el-input {
  width: 300px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}

.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

/* + 样式 */

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style >
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.el-dialog {
  margin-top: 50px;
}
</style>